package examples.stateless;

import java.util.Collection;
import java.util.Date;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import examples.model.Customer;
import examples.model.Performance;
import examples.model.Seat;
import examples.model.Ticket;

@Stateless
public class TicketServiceBean implements TicketService {
    @PersistenceContext(unitName="TicketService")
    protected EntityManager em;


	@Override
	public Collection<Performance> findPerformanceByShowName(String showName) {
		return Performance.findPerformanceByShowName(showName);
	}

	@Override
	public Collection<Performance> findPerformanceByShowNameAndDate(
			String showName, Date date) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Ticket reserveTicket(String customerName, int performanceId) {
        Ticket ticket = new Ticket();

        Customer customer = Customer.findByName(customerName);
        ticket.setCustomer(customer);
        
        Performance performance = em.find(Performance.class, performanceId);
        Seat seat=Seat.findFirstAvailableSeat(performance);
        ticket.setSeat(seat);
        
        em.persist(ticket);
        
        return ticket;
	}

	@Override
	public void releaseTicket(int ticketId) {
	    em.remove(em.find(Ticket.class, ticketId));
	}

	@Override
	public Ticket buyTicket(int ticketId) {
	    Ticket ticket = em.find(Ticket.class, ticketId);
        ticket.setSellDate(new Date());
        em.persist(ticket);
        
        return ticket;
	}

}
